package org.lgh.juli.logging;

import aQute.bnd.annotation.spi.ServiceConsumer;

import java.lang.reflect.Constructor;
import java.nio.file.FileSystems;
import java.util.ServiceLoader;
import java.util.logging.LogManager;

@ServiceConsumer(value=Log.class)
public class LogFactory {

    /**
     * liang2 start-preinit 饿汉式单例模式，实例化一个日志工厂
     *
     */
    private static final LogFactory singleton = new LogFactory();

    /**
     * liang4 start-preinit 日志构造器类型
     * 定义一个构造器类型的代码
     */
    private final Constructor<? extends Log> discoveredLogConstructor;

    /**
     * Private constructor that is not available for public use.
     */
    private LogFactory() {
        /*
         * Work-around known a JRE bug.
         * https://bugs.openjdk.java.net/browse/JDK-8194653
         *
         * Pre-load the default file system. No performance impact as we need to
         * load the default file system anyway. Just do it earlier to avoid the
         * potential潜在的 deadlock.
         *
         * This can be removed once the oldest JRE supported by Tomcat includes
         * a fix.
         *
         * 这个静态方法会返回一个默认的FileSystem 给 JVM——通常是操作系统默认的文件系统 可以忽略，
         * 有关文件系统相关的底层操作，写不写基本都不影响功能
         */
        FileSystems.getDefault();

        // Look via a ServiceLoader for a Log implementation that has a
        // constructor taking the String name.
        /**
         *  liang3 start-preinit SPI机制来加载日志实现类
         * 这段代码时典型的SPI机制来加载日志实现类，但是tomcat中没有使用，不会进入for循环
         * 使用SPI可参照以下代码
         * SPI全称Service Provider Interface，是Java提供的一套用来被第三方实现或者扩展的API，
         * 它可以用来启用框架扩展和替换组件（解耦和可插拔）。
         * Java SPI 实际上是“基于接口的编程＋策略模式＋配置文件”组合实现的动态加载机制。
         *
         * spi内部逻辑是：加载对应配置下配置文件，一行行读取实现类全限定名
         * 然后调用 c = Class.forName(cn, false, loader);真正获取class,懒加载的方式
         *
         *  以下是关于spi机制的描述
         *  https://baijiahao.baidu.com/s?id=1784912053405285180&wfr=spider&for=pc
         *  https://blog.csdn.net/Hellowenpan/article/details/101112365
         *
         *
         *  还有另外一种写法：
         *      ServiceLoader<Driver> loader = ServiceLoader.load(Driver.class);
         *         Iterator<Driver> iterator = loader.iterator();
         *
         *         while (iterator.hasNext()){
         *             Driver driver = iterator.next();
         *             System.out.println("driver : " + driver.getClass() + "loader ：" + driver.getClass().getClassLoader());
         *         }
         */
        ServiceLoader<Log> logLoader = ServiceLoader.load(Log.class);
        System.out.println(Thread.currentThread().getContextClassLoader());
        Constructor<? extends Log> m=null;
        for (Log log: logLoader) {
            Class<? extends Log> c=log.getClass();
            try {
                m=c.getConstructor(String.class);
                break;
            }
            catch (NoSuchMethodException | SecurityException e) {
                throw new Error(e);
            }
        }
        discoveredLogConstructor=m;
    }

    // --------------------------------------------------------- Public Methods

    // only those 2 methods need to change to use a different direct logger.

    /**
     * liang5 start-preinit 获取日志实例
     * 如果使用了SPI机制会加载扩展的日志实现类，没有则直接使用JDK日志，返回对应的日志实例
     * <p>Construct (if necessary) and return a <code>Log</code> instance,
     * using the factory's current set of configuration attributes.</p>
     *
     * <p><strong>NOTE</strong> - Depending upon the implementation of
     * the <code>LogFactory</code> you are using, the <code>Log</code>
     * instance you are returned may or may not be local to the current
     * application, and may or may not be returned again on a subsequent
     * call with the same name argument.</p>
     *
     * @param name Logical name of the <code>Log</code> instance to be
     *  returned (the meaning of this name is only known to the underlying
     *  logging implementation that is being wrapped)
     *
     * @return A log instance with the requested name
     *
     * @exception LogConfigurationException if a suitable <code>Log</code>
     *  instance cannot be returned
     */
    public Log getInstance(String name) throws LogConfigurationException {
        if (discoveredLogConstructor == null) {
            return DirectJDKLog.getInstance(name);
        }

        try {
            return discoveredLogConstructor.newInstance(name);
        } catch (ReflectiveOperationException | IllegalArgumentException e) {
            throw new LogConfigurationException(e);
        }
    }


    /**
     * Convenience method to derive a name from the specified class and
     * call <code>getInstance(String)</code> with it.
     *
     * @param clazz Class for which a suitable Log name will be derived
     *
     * @return A log instance with a name of clazz.getName()
     *
     * @exception LogConfigurationException if a suitable <code>Log</code>
     *  instance cannot be returned
     */
    public Log getInstance(Class<?> clazz) throws LogConfigurationException {
        return getInstance( clazz.getName());
    }


    // ------------------------------------------------------- Static Variables


    // --------------------------------------------------------- Static Methods


    /**
     * liang2 start-preinit 饿汉式单例模式，实例化一个日志工厂，
     *
     * <p>Construct (if necessary) and return a <code>LogFactory</code>
     * instance, using the following ordered lookup procedure to determine
     * the name of the implementation class to be loaded.</p>
     * <ul>
     * <li>The <code>org.lgh.commons.logging.LogFactory</code> system
     *     property.</li>
     * <li>The JDK 1.3 Service Discovery mechanism</li>
     * <li>Use the properties file <code>commons-logging.properties</code>
     *     file, if found in the class path of this class.  The configuration
     *     file is in standard <code>java.util.Properties</code> format and
     *     contains the fully qualified name of the implementation class
     *     with the key being the system property defined above.</li>
     * <li>Fall back to a default implementation class
     *     (<code>org.lgh.commons.logging.impl.LogFactoryImpl</code>).</li>
     * </ul>
     *
     * <p><em>NOTE</em> - If the properties file method of identifying the
     * <code>LogFactory</code> implementation class is utilized, all of the
     * properties defined in this file will be set as configuration attributes
     * on the corresponding <code>LogFactory</code> instance.</p>
     *
     * @return The singleton LogFactory instance
     *
     * @exception LogConfigurationException if the implementation class is not
     *  available or cannot be instantiated.
     */
    public static LogFactory getFactory() throws LogConfigurationException {
        return singleton;
    }


    /**
     * Convenience method to return a named logger, without the application
     * having to care about factories.
     *
     * @param clazz Class from which a log name will be derived
     *
     * @return A log instance with a name of clazz.getName()
     *
     * @exception LogConfigurationException if a suitable <code>Log</code>
     *  instance cannot be returned
     */
    public static Log getLog(Class<?> clazz)
            throws LogConfigurationException {
        return getFactory().getInstance(clazz);
    }


    /**
     * Convenience method to return a named logger, without the application
     * having to care about factories.
     *
     * @param name Logical name of the <code>Log</code> instance to be
     *  returned (the meaning of this name is only known to the underlying
     *  logging implementation that is being wrapped)
     *
     * @return A log instance with the requested name
     *
     * @exception LogConfigurationException if a suitable <code>Log</code>
     *  instance cannot be returned
     */
    public static Log getLog(String name)
            throws LogConfigurationException {
        return getFactory().getInstance(name);
    }

    /**
     * Release any internal references to previously created {@link LogFactory}
     * instances that have been associated with the specified class loader
     * (if any), after calling the instance method <code>release()</code> on
     * each of them.
     *
     * @param classLoader ClassLoader for which to release the LogFactory
     */
    public static void release(ClassLoader classLoader) {
        // JULI's log manager looks at the current classLoader so there is no
        // need to use the passed in classLoader, the default implementation
        // does not so calling reset in that case will break things
        if (!LogManager.getLogManager().getClass().getName().equals(
                "java.util.logging.LogManager")) {
            LogManager.getLogManager().reset();
        }
    }
}
